package com.example.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Slf4j
public class HttpUtils {

    private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        // use the TrustSelfSignedStrategy to allow Self Signed Certificates
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build();

        // we can optionally disable hostname verification.
        // if you don't want to further weaken the security, you don't have to include
        // this.
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();

        // create an SSL Socket Factory to use the SSLContext with the trust self signed
        // certificate strategy
        // and allow all hosts verifier.
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);

        // finally create the HttpClient using HttpClient factory methods and assign the
        // ssl socket factory
        return HttpClients.custom().setSSLSocketFactory(connectionFactory).build();
    }


    public static RequestConfig buildRequestTimeoutConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(3000)
                .setConnectionRequestTimeout(5000).build();
    }


    public static void postJson(String url, String json) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            HttpPost httpPost = new HttpPost(url);

            log.info("start post: {}", json);

            StringEntity stringEntity = new StringEntity(json);
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-type", "application/json");

            httpPost.setConfig(buildRequestTimeoutConfig());

            response = httpClient.execute(httpPost);


        } catch (IOException e) {
            log.error("post to: {} error", url, e.getLocalizedMessage());
        } finally {
            HttpClientUtils.closeQuietly(httpClient);
            HttpClientUtils.closeQuietly(response);
        }
    }


    public static String getJson(String url, Map<String,String> headers) {

        return getJson(url, headers, null);
    }

    public static String getJson(String url, Map<String,String> headers, Map<String, String> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();;
        CloseableHttpResponse response = null;

        try {

            URIBuilder builder = new URIBuilder(url);
            if(params != null && !params.isEmpty()) {
                params.forEach(builder::addParameter);
            }

            HttpGet httpGet = new HttpGet(builder.build());

            httpGet.addHeader(HttpHeaders.ACCEPT, "application/json");

            if(headers != null && !headers.isEmpty()) {
                headers.forEach(httpGet::addHeader);
            }

            httpGet.setConfig(buildRequestTimeoutConfig());
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            log.error("get url: {} error", url, e.getLocalizedMessage());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpClient);
            HttpClientUtils.closeQuietly(response);
        }

        return null;
    }



    public static ByteBuf download(String url)  {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        ByteBuf byteBuf = null;

        String error;

        try {
            httpClient = HttpClients.createDefault();

            HttpGet httpget = new HttpGet(url);
            httpget.setConfig(buildRequestTimeoutConfig());
            response = httpClient.execute(httpget);

            if(response.getStatusLine().getStatusCode() == 200) {
               return Unpooled.wrappedBuffer(EntityUtils.toByteArray(response.getEntity()));
            } else {
                error = "返回码 " + response.getStatusLine().getStatusCode();
                log.error("download {} response error: {}", url, response);
            }
        } catch (IOException e) {
            error = e.getMessage();
            log.error("download {} error", url, e);
        } finally {
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        throw new RuntimeException("下载升级包出错, url: " + url + error);
    }
}
